<template>
  <div class="page-container">
    <div class="form-container">
      <el-form :inline="true" label-width="80px" :size="'small'" ref="form">
        <el-row>
          <el-col :span="6">
            <el-form-item label="合同单号">
              <el-input v-model="state.query.blNo" clearable placeholder="请输入" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户合同号">
              <el-input v-model="state.query.blN" clearable placeholder="请输入" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户">
              <el-select remote-show-suffix v-model="state.query.CustomId" placeholder="请选择客户" style="width: 100%"
                clearable filterable remote :remote-method="getCustomData" :loading="state.currentLoading">
                <el-option v-for="item in state.clientList" :key="item.id" :label="item.comNameCn" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运输方式">
              <el-select remote-show-suffix v-model="state.query.salesman" placeholder="请选择运输方式" style="width: 100%"
                clearable filterable remote :remote-method="getUserData" :loading="state.salesmanLoading">
                <el-option v-for="item in state.salesman" :key="item.id" :label="item.realName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="部门">
              <!-- <el-select remote-show-suffix v-model="state.query.department" placeholder="请选择部门" style="width: 100%"
                clearable filterable remote :loading="state.currentLoading">
                <el-option v-for="item in state.department" :key="item.value" :label="item.label" :value="item.value">
                  <span style="float: left"> {{ item.label }}</span>
                </el-option>
              </el-select> -->
              <el-tree-select v-model="state.query.department" :data="state.department" :render-after-expand="false"
                style="width: 100%" :props="{ label: 'name', value: 'companyId' }" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员">
              <el-select remote-show-suffix v-model="state.query.salesman" placeholder="请选择业务员" style="width: 100%"
                clearable filterable remote :remote-method="getUserData" :loading="state.salesmanLoading">
                <el-option v-for="item in state.salesman" :key="item.id" :label="item.realName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="币种">
              <el-select remote-show-suffix v-model="state.query.currency" placeholder="请选择币种" style="width: 100%"
                clearable filterable remote :remote-method="getCurrentData" :loading="state.currentLoading">
                <el-option v-for="item in state.current" :key="item.value" :label="item.label" :value="item.value">
                  <span style="float: left"> {{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单状态">
              <el-select v-model="state.query.orderState" placeholder="请选择" style="width: 100%" clearable filterable>
                <el-option label="全部" :value="1" />
                <el-option label="草稿" :value="2" />
                <el-option label="已审核" :value="3" />
                <el-option label="待审核" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-collapse-transition>
          <div v-show="state.hidden">
            <el-row>
              <el-col :span="6">
                <el-form-item label="订单日期">
                  <el-date-picker v-model="recDateTime" type="daterange" range-separator="~" start-placeholder="开始日期"
                    end-placeholder="结束日期" size="small" style="width: 100%" clearable value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-collapse-transition>
        <div class="flex-container" style="margin-left: 20px">
          <el-button type="primary" icon="search" @click="getList" size="small">
            搜索
          </el-button>
          <el-button type="info" icon="refresh" @click="reset" size="small">
            重置
          </el-button>
          <el-button type="primary" @click="state.hidden = !state.hidden" size="small" style="padding: 8px 15px">
            <div class="flex-container">
              <el-icon style="transform: rotate(90deg)">
                <MoreFilled />
              </el-icon>
              {{ state.hidden ? "折叠" : "更多条件" }}
            </div>
          </el-button>
        </div>
      </el-form>
    </div>
    <div class="tableDiv">
      <div class="btns">
        <div class="left">
          <el-button @click="toEditPage(null, 2, true)" type="primary">创建合同</el-button>
          <el-button @click="copy" type="primary">复制</el-button>
        </div>
        <div class="right">
          <el-dropdown>
            <el-button type="primary">
              确认审核<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="confirmAudit(1)">已审核</el-dropdown-item>
                <el-dropdown-item @click="confirmAudit(0)">待审核</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button @click="customOpen">自定义列</el-button>
          <el-button @click="draggbaleItem">删除</el-button>
          <el-button @click="refresh" icon="RefreshRight">刷新</el-button>
        </div>
      </div>
      <!-- <AppPageTable ref="tableRef" stripe :data="state.tableData.data" @change="getList" :height="0"
        :option="state.tableData.option" v-loading="state.tableLoading">
        <el-table-column type="selection" width="40" align="center" fixed="left" />
        <el-table-column sortable v-for="item in state.customColumn" :key="item.prop" :prop="item.prop"
          :label="item.label" align="center" showOverflowTooltip>
          <template v-if="item.prop === 'blNo'" #default="{ row }">
            <span style="color: #5a9cf8; cursor: pointer" @click="toEditPage(row.blNo, row.contractState)">{{
              row.blNo }}</span>
          </template>
          <template v-if="item.prop === 'company'" #default="{ row }">
            <span>{{ row.company }}</span>
          </template>
          <template v-if="item.prop === 'address'" #default="{ row }">
            <span>{{ row.address }}</span>
          </template>
          <template v-if="item.prop === 'client'" #default="{ row }">
            <span>{{ row.client }}</span>
          </template>
          <template v-if="item.prop === 'clientAddress'" #default="{ row }">
            <span>{{ row.clientAddress }}</span>
          </template>
          <template v-if="item.prop === 'tradeTerms'" #default="{ row }">
            <span>{{ row.tradeTerms }}</span>
          </template>
          <template v-if="item.prop === 'shipping'" #default="{ row }">
            <span>{{ row.shipping }}</span>
          </template>
          <template v-if="item.prop === 'destination'" #default="{ row }">
            <span>{{ row.destination }}</span>
          </template>
          <template v-if="item.prop === 'contractState'" #default="{ row }">
            <div style="display: flex;align-items: center;">
              <div :style="row.contractState === 1 ? 'background: #248BFF' : 'background: #969799'"
                style="width: 6px;height: 6px;border-radius: 50%;margin-right: 5px;" class="left"></div>
              <div :style="row.contractState === 1 ? 'color: #000000' : 'color: #969799'" class="right">
                {{ contractState[row.contractState] }}
              </div>
            </div>
          </template>
          <template v-if="item.prop === 'orderState'" #default="{ row }">
            <div style="display: flex;align-items: center;">
              <div :style="row.orderState === 1 ? 'background: #248BFF' : 'background: #969799'"
                style="width: 6px;height: 6px;border-radius: 50%;margin-right: 5px;" class="left"></div>
              <div :style="row.orderState === 1 ? 'color: #000000' : 'color: #969799'" class="right">{{
                row.orderState
                === 1 ? '待订舱' : '草稿' }}</div>
            </div>
          </template>

        </el-table-column>
      </AppPageTable> -->
      <AppVxeTable class="vex-table-primary" ref="tableRef" stripe :tableData="state.tableData.data" @change="getList"
        :height="0" :tableOption="state.tableData.option" v-loading="state.tableLoading">
        <vxe-column fixed="left" title="复选" type="checkbox" width="40" align="center" />
        <vxe-column sortable v-for="item in state.customColumn" :width="item.width" :key="item.prop" :field="item.prop"
          :title="item.label">
          <template v-if="item.prop === 'blNo'" #default="{ row }">
            <span style="color: #5a9cf8; cursor: pointer" @click="toEditPage(row.blNo, row.contractState)">{{
              row.blNo }}</span>
          </template>
          <template v-if="item.prop === 'company'" #default="{ row }">
            <span>{{ row.company }}</span>
          </template>
          <template v-if="item.prop === 'address'" #default="{ row }">
            <span>{{ row.address }}</span>
          </template>
          <template v-if="item.prop === 'client'" #default="{ row }">
            <span>{{ row.client }}</span>
          </template>
          <template v-if="item.prop === 'clientAddress'" #default="{ row }">
            <span>{{ row.clientAddress }}</span>
          </template>
          <template v-if="item.prop === 'tradeTerms'" #default="{ row }">
            <span>{{ row.tradeTerms }}</span>
          </template>
          <template v-if="item.prop === 'shipping'" #default="{ row }">
            <span>{{ row.shipping }}</span>
          </template>
          <template v-if="item.prop === 'destination'" #default="{ row }">
            <span>{{ row.destination }}</span>
          </template>
          <template v-if="item.prop === 'contractState'" #default="{ row }">
            <div style="display: flex;align-items: center;">
              <div :style="row.contractState === 1 ? 'background: #248BFF' : 'background: #969799'"
                style="width: 6px;height: 6px;border-radius: 50%;margin-right: 5px;" class="left"></div>
              <div :style="row.contractState === 1 ? 'color: #000000' : 'color: #969799'" class="right">
                {{ contractState[row.contractState] }}
              </div>
            </div>
          </template>
          <template v-if="item.prop === 'orderState'" #default="{ row }">
            <div style="display: flex;align-items: center;">
              <div :style="row.orderState === 1 ? 'background: #248BFF' : 'background: #969799'"
                style="width: 6px;height: 6px;border-radius: 50%;margin-right: 5px;" class="left"></div>
              <div :style="row.orderState === 1 ? 'color: #000000' : 'color: #969799'" class="right">{{
                row.orderState
                === 1 ? '待订舱' : '草稿' }}</div>
            </div>
          </template>

        </vxe-column>
      </AppVxeTable>

      <!-- <AppVxeTable :rowId="'Id'" ref="ContractTableRef" :tableHeaderKey="'ContractRefTable'" :toolbarConfig="true"
        class="vex-table-primary" :tableHeight="state.clientHeight"
        :tableVisible="state.tableData.data.length || state.tableLoading == true" :tableData="state.tableData.data"
        :tableOption="state.tableData.option" :hasCheckBox="true" @getTableList="getList" v-loading="state.tableLoading">
        <template #leftBtnGroup>
          <div class="workbench-second-title">
            <el-button class="btn-mini-size" type="primary" @click="copyFreight2()" :loading="state.btnLoading">
              快速报价</el-button>
            <el-button class="btn-mini-size" type="primary" @click="newCopyFreight2()" :loading="state.btnLoading2">
              模板快速报价</el-button>
          </div>
        </template>
        <template #rightBtnGroup>
          <el-button icon="el-icon-refresh-right" class="left10 btn-mini-size" @click="initList()"
            v-show="state.tableData.length == 0">刷新</el-button>
        </template>

        <vxe-column fixed="left" title="复选" type="checkbox" width="40"></vxe-column>

        <vxe-column field="UpdateTimeTag" title="合同单号">
          <template #default="{ row }">
            <span>{{ row.UpdateTimeTag }}</span>
          </template>
        </vxe-column>

        <vxe-column field="CompanyName" title="公司" sortable :resizable="true" show-overflow>
          <template #default="{ row }">
            <span>{{ row.CompanyName }}</span>
          </template>
        </vxe-column>

        <vxe-column field="UpdateTimeTag" title="客户合同号">
          <template #default="{ row }">
            <span>{{ row.UpdateTimeTag }}</span>
          </template>
        </vxe-column>

        <vxe-column field="UpdateTimeTag" title="合同审核状态">
          <template #default="{ row }">
            <span>{{ row.UpdateTimeTag }}</span>
          </template>
        </vxe-column>

        <vxe-column field="UpdateTimeTag" title="中信保是否介入">
          <template #default="{ row }">
            <span>{{ row.UpdateTimeTag }}</span>
          </template>
        </vxe-column>

        <vxe-column field="UpdateTimeTag" title="中信保审核状态">
          <template #default="{ row }">
            <span>{{ row.UpdateTimeTag }}</span>
          </template>
        </vxe-column>

      </AppVxeTable> -->
    </div>
    <el-dialog class="dialog" v-model="state.custom.show" title="自定义列" width="800" :before-close="customHandleClose">
      <Draggbale ref="draggbale" :items="state.customColumn"></Draggbale>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetDraggbale">重置</el-button>
          <el-button @click="customHandleClose">取消</el-button>
          <el-button type="primary" @click="customHandleClose">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from "vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import request from "@/public/request";
import { MoreFilled } from "@element-plus/icons";
import { fileDownload } from "@/public/publicUtils";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import AppVxeTable from "@/components/AppVxeTable.vue";
import Draggbale from './components/draggbale.vue'

const Router = useRouter();

//审核状态
let contractState = {
  0: '待审核',
  1: '已审核',
  2: '草稿'
}

const state = reactive({
  clientHeight: document.body.clientHeight - 250,
  // 查询条件
  query: {
    entId: "",  //合同类别
    blNo: "",    //合同单号
    blN: "",   //客户合同号
    CustomId: "",    //客户
    department: "",   //部门
    salesman: "",    //业务员
    currency: "",   //币种
    orderState: ""  //订单状态
  },
  //自定义列
  customColumn: [
    { prop: "blNo", label: "合同单号", width: "155" },
    { prop: "company", label: "公司", width: "155" },
    { prop: "address", label: "公司地址", width: "155" },
    { prop: "client", label: "客户", width: "155" },
    { prop: "clientAddress", label: "客户地址", width: "155" },
    { prop: "contractState", label: "合同状态", width: "155" },
    { prop: "orderState", label: "订单状态", width: "155" },
    { prop: "tradeTerms", label: "贸易条款", width: "155" },
    { prop: "shipping", label: "运输方式", width: "155" },
    { prop: "destination", label: "运抵国", width: "155" },
  ],
  //表格数据
  tableData: {
    data: [
      { blNo: 'JH2401878', company: '君禾泵业股份有限公司', address: 'SD240410+11', client: 'Glong italy srl', clientAddress: 'Glong italy srl', contractState: 1, orderState: 1, tradeTerms: '外销促销订单', shipping: '水路运输', destination: 'POLAND', isDraft: false },
      { blNo: 'JH2401878', company: '君禾泵业股份有限公司', address: 'SD240410+11', client: 'Glong italy srl', clientAddress: 'Glong italy srl', contractState: 0, orderState: 1, tradeTerms: '外销促销订单', shipping: '水路运输', destination: 'POLAND', isDraft: true },
      { blNo: 'JH2401878', company: '君禾泵业股份有限公司', address: 'SD240410+11', client: 'Glong italy srl', clientAddress: 'Glong italy srl', contractState: 1, orderState: 1, tradeTerms: '外销促销订单', shipping: '水路运输', destination: 'POLAND', isDraft: false },
      { blNo: 'JH2401878', company: '君禾泵业股份有限公司', address: 'SD240410+11', client: 'Glong italy srl', clientAddress: 'Glong italy srl', contractState: 2, orderState: 0, tradeTerms: '外销促销订单', shipping: '水路运输', destination: 'POLAND', isDraft: true },
    ],
    option: useTableOption(),
  },
  tableLoading: false,
  // 展开
  hidden: false,
  // 币种
  current: [],
  // 业务员下拉框
  salesman: [],
  salesmanLoading: false,
  // 币种数组
  curList: [],
  currentLoading: false,
  show: false,
  //客户下拉框
  clientList: [],
  clientLoading: false,
  //部门tree
  department: [],
  //自定义列数据
  custom: {
    show: false,
    data: []
  },
});

//拖拽组件ref
const draggbale = ref()

//tableRef
const tableRef = ref()

// 跳转外来合同详情页面
const toEditPage = async (id, contractState, isNew) => {
  Router.openTab({
    path: "/exportContract/exportContractBusiness/ForeignContractDetail",
    query: {
      id: id,
      title: id ? `外来合同详情${id}` : '创建外来合同',
      // isDraft: isDraft,
      contractState,
      isNew
      // iscopy: false,
      // tab: '费用信息'
    },
  });
  // console.log(isDraft);
};

//自定义列dialog打开
function customOpen() {
  state.custom.show = true
}

//自定义列dialog关闭
function customHandleClose() {
  state.custom.show = false
}

//删除按钮
function draggbaleItem() {
  if (state.tableData.option.selected.length == 0) {
    return ElMessage.warning('请选择数据')

  }
  ElMessageBox.confirm(
    '是否删除?',
    '提示',
    {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    }
  ).then(() => {
    state.tableData.data = state.tableData.data.filter(item => !state.tableData.option.selected.includes(item))
    state.tableData.option.selected = []
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消成功',
    })
  })
  console.log(draggbale.value.getItems());
}

//重置自定义列
function resetDraggbale() {
  ElMessage.success('重置成功')
}

//刷新
function refresh() {
  ElMessage.success('刷新成功')
}


// 获取币种类型
const getCurrentData = async (val) => {
  state.currentLoading = true;
  let res = await request.get("/api/base/currency/dropdownlist", {
    keywords: val,
  });
  state.current = res.map((item) => {
    return {
      label: item.currencyCode + "|" + item.currencyName,
      value: item.currencyCode,
    };
  });
  console.log(state.current);
  state.currentLoading = false;
}

// 获取客户信息
const getCustomData = async (val) => {
  state.clientLoading = true;
  let res = await request.get("/api/crcontactcompany/querypagedto", {
    PageIndex: 1,
    PageSize: 15,
    ComNameCn: val,
  });
  console.log(res)
  state.clientList = res.content;
  state.clientLoading = false;
};

// 获取业务员信息
const getUserData = async (val) => {
  state.salesmanLoading = true;
  let res = await request.get("/api/user/query", {
    PageIndex: 1,
    PageSize: 15,
    KeyWords: val,
  });
  state.salesman = res.content;
  state.salesmanLoading = false;
};

//部门tree
const getdepartmentTree = async () => {
  const res = await request.get('/api/department/buildTree')
  console.log(res)
  state.department = res
}


//审核
function confirmAudit(num) {
  if (state.tableData.option.selected.length == 0) {
    return ElMessage.warning('请选择数据')
  }
  if (num == 1) {
    try {
      state.tableData.data.forEach((item) => {
        state.tableData.option.selected.forEach(i => {
          if (item == i) {
            if (item.contractState == 1) {
              throw new Error('列表中有合同已审核，不能再次审核')
            }
            item.contractState = 1
            item.orderState = 1
          }
        })
      })
      ElMessage.success('审核成功')
    } catch (error) {
      ElMessage.warning(error.message)
    }
  } else {
    try {
      state.tableData.data.forEach((item) => {
        state.tableData.option.selected.forEach(i => {
          if (item == i) {
            if (item.contractState == 0) {
              throw new Error('列表中有合同未审核，不能驳回审核')
            }
            item.contractState = 0
            item.orderState = 0
          }
        })
      })
      ElMessage.success('驳回成功')
    } catch (error) {
      ElMessage.warning(error.message)
    }
  }
}

//复制
function copy() {
  if (state.tableData.option.selected.length == 0) {
    return ElMessage.warning('请选择数据')
  }
  console.log(state.tableData.option.selected)
  state.tableData.option.selected.forEach(item => [
    state.tableData.data.push({
      address: item.address,
      blNo: item.blNo,
      client: item.client,
      clientAddress: item.clientAddress,
      company: item.company,
      destination: item.destination,
      isDraft: true,
      shipping: "水路运输",
      tradeTerms: "外销促销订单",
      contractState: 2,
      orderState: 0
    })
  ])
}

//获取列表
function getList() {

}

//重置
function reset() {
  state.query = {
    entId: "",  //合同类别
    blNo: "",    //合同单号
    blN: "",   //客户合同号
    CustomId: "",    //客户
    department: "",   //部门
    salesman: "",    //业务员
    currency: "",   //币种
    orderState: ""  //订单状态
  }
}

onMounted(() => {
  getdepartmentTree()
})

</script>

<style lang="scss" scoped>
.form-container {
  border: 1px solid #e8e8e8;
  padding: 6px 6px 6px 8px;
  background-color: #ffffff;

  :deep(.el-form-item--small .el-form-item__label) {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.85);
  }

  :deep(.el-input--suffix .el-input__inner) {
    padding-right: 4px;
  }

  :deep(.el-form--inline .el-form-item) {
    display: flex;
    margin-right: 0;
  }

  :deep(.el-form-item--small.el-form-item) {
    margin-bottom: 8px;
  }
}

:deep(.el-checkbox.el-checkbox--large) {
  height: 0px;
}

:deep(.el-dialog__footer) {
  padding-bottom: 10px;
  text-align: center;
}

:deep(.el-table__cell) {
  height: auto;
}

:deep(.el-dropdown) {
  margin-right: 10px;
}

.tableDiv {
  box-sizing: border-box;
  width: 100%;
  padding: 8px 12px;
  margin-top: 8px;
  background-color: #ffffff;

  .btns {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 28px;
    // background-color: aqua;
    margin-bottom: 10px;
  }
}

:deep(.el-dialog) {
  padding: 0 0;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e8e8e8;
  padding: 7px 12px;
  font-family: 800;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #e8e8e8;
  padding: 8px 0;
  text-align: center;
}
</style>
